package converter;

import converter.StringBaseEnum;
import exception.TypeConversionException;
import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;

import static content.common.ExceptionMessage.PARAMS_ENUM_NOT_MATCH;

/**
 * String转换成枚举类型
 * @param <E>
 */
public class StringToEnumConverter<E extends StringBaseEnum> implements Converter<String, E> {
    HashMap<String, E> enumMap = new HashMap<>();

    public StringToEnumConverter(Class<E> enumType) {
        E[] constants = enumType.getEnumConstants();
        for (E constant : constants) {
            enumMap.put(constant.getName(), constant);
        }
    }

    @Override
    public E convert(String source) {
        E e = enumMap.get(source);
        if (e==null){
            throw new TypeConversionException(PARAMS_ENUM_NOT_MATCH);
        }
        return e;
    }
}
